/**
 * @author Loan
 */
package controller;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.Activity;
import android.app.AlertDialog;
import android.dbhelper.AccountDbHelper;
import android.fourrows.R;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class Register extends Activity{
	public Button mRegisterBtn;
	public Button mCancelBtn;
	protected EditText mUsername;
	protected EditText mPwd;
	protected EditText mConfirmPwd;
	protected EditText mEmail = null;
	public static final String NOTICE ="Notice";
	public static final String DEBUG_TAG="REGISTER DEBUG";
	//create an anonymous implementation of OnClickListenerr
	protected OnClickListener mButton = new OnClickListener(){
			public void onClick(View v){
				switch(v.getId()){
				case R.id.register_ok_button:
					Log.i(DEBUG_TAG,"Hit register button");
					int usernameLen = mUsername.getText().length();
					int pwdLen = mPwd.getText().length();
					int pwdLen1 = mConfirmPwd.getText().length();
					String pwd = mPwd.getText().toString();
					String conPwd = mConfirmPwd.getText().toString();
					if (usernameLen < 6 || pwdLen < 6 || pwdLen1 < 6  ){
						createDialog(NOTICE, "Username and password is at least 6 characters");
					}else if( ! isEmailAddress(mEmail.getText().toString())){
						createDialog(NOTICE, "Invalid email!");
					}
					else if ( pwd.equals(conPwd) == false){
						createDialog(NOTICE, "Password's not matched");
					}else{
					//	registerForUser(mUsername.getText().toString(),md5(mPwd.getText().toString()),mEmail.getText().toString());
						AccountDbHelper account = new AccountDbHelper();
						boolean result = 
								account.actionRegister(mUsername.getText().toString(),md5(mPwd.getText().toString()),mEmail.getText().toString());
						if (result == true){
							createDialog("Success","Your register is successfull");
							//Intent hello_screen_intent = new Intent(this, Login.class);
							//startActivity(hello_screen_intent);
						}else{
							createDialog(NOTICE, "This username or email is used,please choose another!");
						}
					}
					
					break;
				case R.id.register_cancel_button:
					Log.i(DEBUG_TAG,"Hit cancel button");
					finish();
					break;
				default: break;
				}
			}

		};
		protected void createDialog(String title, String text) {
			AlertDialog ad = new AlertDialog.Builder(this)
					.setPositiveButton("Ok", null).setTitle(title).setMessage(text)
					.create();

			ad.show();
		}
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.register);
		mUsername = (EditText)findViewById(R.id.et_register_username);
		mPwd = (EditText)findViewById(R.id.et_register_password);
		mConfirmPwd = (EditText)findViewById(R.id.et_register_password2);
		mEmail = (EditText)findViewById(R.id.et_register_email);
		mRegisterBtn = (Button)findViewById(R.id.register_ok_button);
		mRegisterBtn.setOnClickListener(mButton);
		mCancelBtn = (Button)findViewById(R.id.register_cancel_button);
		mCancelBtn.setOnClickListener(mButton);
	}

    protected boolean isEmailAddress(String emailAddress) {
		if (emailAddress == null) return false;
	    String  expression="^[\\w\\-]([\\.\\w])+[\\w]+@([\\w\\-]+\\.)+[A-Z]{2,4}$";  
	    CharSequence inputStr = emailAddress;  
	    Pattern pattern = Pattern.compile(expression,Pattern.CASE_INSENSITIVE);  
	    Matcher matcher = pattern.matcher(inputStr);  
	    return matcher.matches(); 
	}
    
    /** A md5 code from the internet !*/
	protected String md5(String pass) {
		  MessageDigest digest;
	        try {
	            digest = MessageDigest.getInstance("MD5");
	            digest.reset();        
	            digest.update(pass.getBytes());
	            byte[] a = digest.digest();
	            int len = a.length;
	            StringBuilder sb = new StringBuilder(len << 1);
	            for (int i = 0; i < len; i++) {
	                sb.append(Character.forDigit((a[i] & 0xf0) >> 4, 16));
	                sb.append(Character.forDigit(a[i] & 0x0f, 16));
	            }
	            return sb.toString();
	        } catch (NoSuchAlgorithmException e) { e.printStackTrace(); }
	        return null;
	}

}
